import {
    createSlice,
    createAsyncThunk
} from "@reduxjs/toolkit";
import {useSelector} from "react-redux";
import {message} from "antd";
import {getInfo, postLogin, postLogout} from "@/api/auth";
import {useNavigate} from "react-router-dom";

const authSlice = createSlice({
    name:"auth",
    initialState:{
        token:localStorage.getItem("token"),
        info:localStorage.info?JSON.parse(localStorage.info):{},
        isLoading:false
    },
    reducers:{
        clearState(state,{payload}){
            localStorage.clear();
            state.info = state.token = payload;
        },
        upInfo(state,{payload}){
            localStorage.setItem("info",JSON.stringify(payload));
            state.info = payload;
        },
        upToken(state,{payload}){
            state.token = localStorage.token = payload;
        }
    },
    extraReducers(buildes){
        buildes.addCase(postLoginAsync2.fulfilled,function useMy(state:any,action:any){
            // console.log(2222,action);// {type:"aaaa/fulfilled",payload:result}
            message.success(action.payload.message)
            state.isLoading = false;
            state.token = localStorage.token = action.payload.data.token;

        }).addCase(postLoginAsync2.pending,(state,action)=>{
            // console.log("pending",action)
            state.isLoading = true;
        })
        .addCase(postLoginAsync2.rejected,(state,action:any)=>{
            state.isLoading = false;
        })
    }
})
const {upToken,upInfo,clearState} = authSlice.actions;
// 1
export const postLoginAsync1 = function(values:any){
    return async (dispatch:any)=>{
        const result = await postLogin(values);
        dispatch(upToken(result.data.token));
        return result;
    }
}
// 2- 扩展
// 2-1: createAsyncThunk是一个函数
// 2-2: 接收两个参数：第一个参数是字符串，第二个参数是一个回调函数
// 2-3:特点：
//    可以通过dispatch接收postLoginAsync2返回的结果： dispatch(postLoginAsync2());
//    可以执行到createAsyncThunk指定的第二个参数（回调函数）
export const postLoginAsync2 = createAsyncThunk("aaaa",async (values:any)=>{
    const result =  await postLogin(values);
    return result;
});// dispatch(postLoginAsync2(11))

// 获取个人信息
export const getInfoAsync = ()=>{
    return async (dispatch:any,getState:any)=>{
        const state = getState();
        if(state.auth.info.name){
            return;
        }
        const result =  await getInfo();
        dispatch(upInfo({
            name:result.data.name,
            avatar:result.data.avatar
        }))
    }
}
// 退出登陆
export const postLogoutAsync = ()=>{
    return async (dispatch:any)=>{
        const result = await postLogout();
        dispatch(clearState(null));
    }
}


export const useSelectorAuth = ()=>useSelector((state:any)=>state.auth);
export default authSlice.reducer;